package com.lyhdev.plurk.bot

import java.util.*
import javax.script.*
import org.json.*
import com.google.jplurk.*
import com.google.jplurk.PlurkNotifier.NotificationListener;
import static groovy.io.FileType.*
import static groovy.io.FileVisitResult.*

class Mothership implements NotificationListener {
	
	def API_KEY	= 'CHANGE_HERE'
	def __user	= 'CHANGE_HERE'
	def __pass	= 'CHANGE_HERE'
	
	def __limit	= 100				//Maximum plurks to read at once
	def __sleep = 5000
	
	def is_login = false
	def shutdown = false
	
	def dateoffset = DateTime.now()
	
	def client
	def factory
	def engine
	def cache = [:]
	
	def timer = new Timer()
	
	def Mothership() {
	}
	
	def init() {
		cache['version']	= '1'
		cache['start']		= new Date()
		
		factory = new ScriptEngineManager()
		engine = factory.getEngineByName('groovy')
	
		if (engine) {
			engine.put 'ship', this
			println 'found groovy engine.'
		
			client = new FixPlurkClient(new ISettings.Simple(API_KEY, Lang.tr_ch))
			is_login = client.login(__user, __pass)?true:false
			
			println is_login?'plurk login.':'plurk login error.'
		}
		else {
			println 'could not find groovy engine.'
		}
	}
	
	void onNotification(JSONObject msg) throws Exception {
		println msg;
		
		if (msg.type.equals('new_plurk') && msg.plurk_type.equals(1) && (msg.content =~ '^/[a-zA-Z0-9]+')) {
			// content-type: command
			
			println "command: content"
			
			engine.put 'plurk', msg
			
			new File('commands').traverse(
			        type         : FILES,
			        nameFilter   : ~/.*\.groovy/,
			        sort         : { a, b ->
						a.isFile() != b.isFile() ? a.isFile() <=> b.isFile() : a.name <=> b.name
					}) {
				gf ->
				def reader = gf.newReader('UTF-8')
				try {
					println "command script ${gf}"
					engine.eval reader
				}
				catch (e) {
					println e.message
				}
				reader.close()
			}
		}
		else {
			// content-type: weapon
			
			def matched = 0
			
			engine.put 'plurk', msg.type.equals('new_response')?msg.response:msg
			engine.put 'msg', msg
			engine.put 'matched', matched
			
			new File('weapons').traverse(
			        type         : FILES,
			        nameFilter   : ~/.*\.groovy/,
			        sort         : { a, b ->
						a.isFile() != b.isFile() ? a.isFile() <=> b.isFile() : a.name <=> b.name
					}) {
				gf ->
				def reader = gf.newReader('UTF-8')
				try {
					println "weapon script ${gf}"
					engine.eval reader
				}
				catch (e) {
					println e.message
				}
				reader.close()
			}
		}
	}
	
	def comet() {
		// timer for userchannel loop
		def notifier = client.userChannel
		notifier.addNotificationListener this
		timer.schedule notifier, new Date(), 50 * 1000
		// official suggestion: sleep 50 seconds
	}
	
	def depart() {
		def c = 0
			
		// spider go!
		new File('spiders').traverse(
		        type         : FILES,
		        nameFilter   : ~/.*\.groovy/,
		        sort         : { a, b ->
					a.isFile() != b.isFile() ? a.isFile() <=> b.isFile() : a.name <=> b.name
				}) {
			gf ->
			def reader = gf.newReader('UTF-8')
			try {
				println "spider script ${gf}"
				engine.eval reader
			}
			catch (e) {
				println e.message
			}
			reader.close()
		}
		
		comet();
		
		while (!shutdown) {
			
			// eat foods
			new File('foods').traverse(
			        type         : FILES,
			        nameFilter   : ~/.*\.groovy/,
			        sort         : { a, b ->
						a.isFile() != b.isFile() ? a.isFile() <=> b.isFile() : a.name <=> b.name
					}) {
				gf ->
				def reader = gf.newReader('UTF-8')
				try {
					println "food script ${gf}"
					engine.eval reader
				}
				catch (e) {
					println e.message
				}
				reader.close()
			}
						
			println "round(${c}) complete!"
			
			sleep __sleep
			
			c++
		}
	}
	
	def plurk(text, qualifier) {
		client.plurkAdd text, qualifier
	}
	
	def response(pid, text, qualifier) {
		client.responseAdd "${pid}", text, qualifier
	}
	
	def addAsFriend(uid) {
		client.addAsFriend uid
	}
	
	def removeAsFriend(uid) {
		client.removeAsFriend uid
	}
	
	static main(args) {

		def ship = new Mothership()
		def sysin = new Scanner(System.in)
		
		println 'API-KEY:'
		ship.API_KEY = sysin.nextLine()
		println 'username:'
		ship.__user = sysin.nextLine()
		println 'password:'
		ship.__pass = sysin.nextLine()
		
		ship.init()
		
		if (ship.is_login) {
			ship.depart();
		}
	}
}
